const sql = require('mssql');
const baseFn = require('../../public/base.js');
const fs = require('fs'); // 图片路径
let uploadDir = './images/';


// 存储图片
const storagePic = (file, ind) => {
    let fileName = file.name;
    let newFileName = Date.now() + '_' + ind + fileName;
    let readStream = fs.createReadStream(file.path);
    let writeStream = fs.createWriteStream(uploadDir + newFileName);
    readStream.pipe(writeStream);
    return 'http://www.rsimg.com/' + newFileName
}

// 获取登录用户的部门信息
const getLoginPartInfo = async (ctx, next) => {
    let getBody = ctx.request.body;

    let result = await sql.query(`SELECT B.BM,B.MC FROM BM_YG Y LEFT JOIN BM_BM B ON Y.BMBM = B.BM WHERE Y.BM = '${getBody.userId}'`);
    ctx.body = { result: result.recordset };
}
// 获取检索的客户信息
const getCustomerInfo = async (ctx, next) => {
    let getBody = ctx.request.body;
    let selectSql = `SELECT BM,MC,DH,YUSYE,YINSYE,YINFYE,LJJF,SYJF,WLYE,DWLX,SFZ,DZ,XB,SR FROM BM_WLDW WHERE (DWLX = 3 OR DWLX=4) AND `;
    // 过滤客户信息
    if (getBody.type === 'filter') {
        selectSql += `(BM LIKE '%${getBody.customer}%' OR DH LIKE '%${getBody.customer}%' OR JP LIKE '%${getBody.customer}%')`;
    } else {
        // 通过编码查询详细信息
        selectSql += `BM = '${getBody.customer}' `;
    }
    let result = await sql.query(selectSql);
    ctx.body = { result: result.recordset };
}

// 获取商品的信息
const getStoreShopInfo = async (ctx, next) => {
    let getBody = ctx.request.body;
    let actionSql = '';
    //    为会员的时候去会员价
    if (getBody.DWLX == 3) {
        actionSql = `SELECT Y.SSXK,Y.BM,Y.MC,Y.GG,Y.SCCJ,Y.JLDW,Y.TM,Y.PZWH,Y.YPLX,Y.CCTJ,Y.JXMC,Y.CDMC,Y.MJSL,Y.LSJ,Y.ZDJ,Y.JFGZ,Y.ZPCX,Y.XGSL,Y.YXFL,
        Y.TSFL,T1.KCSL,T1.SCPH,T1.YXQZ,T1.SCRQ,T1.YXQX,T1.CBJJ,T1.CKBM,T1.HWBH,T1.CKMC,isnull(P.HYJ,Y.HYJ) AS DJ  FROM BM_YP Y LEFT JOIN 
        (SELECT * FROM YP_PRICE WHERE BMBM = '${getBody.BMBM}') P ON Y.BM = P.YPBM LEFT JOIN (SELECT KCSL,SCPH,YPBM,YXQZ,SCRQ,YXQX,CBJJ,CKBM,
            CKMC,HWBH FROM KC_KCDTB WHERE BMBM = '${getBody.BMBM}')  T1 ON Y.BM = T1.YPBM WHERE T1.KCSL>0 AND (Y.BM LIKE '%${getBody.shop}%' OR 
            Y.TM LIKE '%${getBody.shop}%' OR Y.MC LIKE '%${getBody.shop}%' OR Y.JP LIKE '%${getBody.shop}%') `
    } else {
        //    不是会员的时候
        actionSql = `SELECT Y.SSXK,Y.BM,Y.MC,Y.GG,Y.SCCJ,Y.JLDW,Y.TM,Y.PZWH,Y.YPLX,Y.CCTJ,Y.JXMC,Y.CDMC,Y.MJSL,Y.LSJ,Y.ZDJ,Y.JFGZ,Y.ZPCX,Y.XGSL,Y.YXFL,
        Y.TSFL,T1.KCSL,T1.SCPH,T1.YXQZ,T1.SCRQ,T1.YXQX,T1.CBJJ,T1.CKBM,T1.HWBH,T1.CKMC,isnull(P.LSJ,Y.LSJ) AS DJ  FROM BM_YP Y LEFT JOIN 
        (SELECT * FROM YP_PRICE WHERE BMBM = '${getBody.BMBM}') P ON Y.BM = P.YPBM LEFT JOIN (SELECT KCSL,SCPH,YPBM,YXQZ,SCRQ,YXQX,CBJJ,CKBM,
            CKMC,HWBH FROM KC_KCDTB WHERE BMBM = '${getBody.BMBM}')  T1 ON Y.BM = T1.YPBM WHERE T1.KCSL>0 AND (Y.BM LIKE '%${getBody.shop}%' 
            OR Y.TM LIKE '%${getBody.shop}%' OR Y.MC LIKE '%${getBody.shop}%' OR Y.JP LIKE '%${getBody.shop}%') `
    }
    let result = await sql.query(actionSql);
    ctx.body = { result: result.recordset };
}
// 选择批号的时候获对应商品的批号信息
const getStoreSalesScph = async (ctx, next) => {
    let getBody = ctx.request.body;
    let actionSql = `SELECT K.KCSL,K.SCPH,K.YPBM,K.YXQZ,K.SCRQ,K.YXQX,Y.MC FROM KC_KCDTB K LEFT JOIN BM_YP Y ON K.YPBM = Y.BM WHERE K.BMBM = '${getBody.BMBM}' AND K.CKBM = '${getBody.CKBM}' AND K.KCSL>0 AND K.YPBM = '${getBody.YPBM}' `;
    let result = await sql.query(actionSql);
    ctx.body = { result: result.recordset };
}
// // 含麻登记
// const containHempRegister = async (ctx, next) => {
//     let getBody = ctx.request.body;
//     let updateSql = `UPDATE BM_WLDW SET MC = '${getBody.MC}',DH = '${getBody.DH}',SFZ = '${getBody.SFZ}',DZ = '${getBody.DZ}' WHERE BM = '${getBody.BM}'`;
//     let result = await sql.query(updateSql);
//     if (result.rowsAffected[0] > 0) {
//         ctx.body = { success: true }
//     } else {
//         ctx.body = { success: false }
//     }
// }
// 获取新的药品价格
const getStoreSalesNewShopPrice = async (ctx, next) => {
    let getBody = ctx.request.body;
    let ypbmStr = getBody.ypbmList.map(item => `'${item}'`).join(',');
    let actionSql = '';
    //    为会员的时候去会员价
    if (getBody.DWLX == 3) {
        actionSql = `SELECT Y.BM,isnull(P.HYJ,Y.HYJ) AS DJ  FROM BM_YP Y LEFT JOIN (SELECT * FROM YP_PRICE WHERE BMBM = '${getBody.BMBM}') P ON Y.BM = P.YPBM WHERE BM IN (${ypbmStr}) `
    } else {
        //    不是会员的时候
        actionSql = `SELECT Y.BM,isnull(P.LSJ,Y.LSJ) AS DJ  FROM BM_YP Y LEFT JOIN (SELECT * FROM YP_PRICE WHERE BMBM = '${getBody.BMBM}') P ON Y.BM = P.YPBM WHERE BM IN (${ypbmStr})`
    }
    let result = await sql.query(actionSql);
    ctx.body = { result: result.recordset };
}

// 获得收款期至
const getMoneyTimeTo = (m) => {
    let timeStamp = new Date().getTime();
    let trasformStamp = m * 86400000;
    let validityTime = new Date(timeStamp + trasformStamp);
    return baseFn.getNowTimeId(validityTime).fullDate
}

// 保存门店销售信息
const keepStoreSalesInfo = async (ctx, next) => {
    const getBody = ctx.request.body;
    let orderId = getBody.hangOrderId;
    let partInfo = JSON.parse(getBody.partInfo);
    let userInfo = JSON.parse(getBody.userInfo);
    let searchVal = JSON.parse(getBody.searchVal);
    let searchTwoVal = JSON.parse(getBody.searchTwoVal);
    let chooseCustomerInfo = searchVal.chooseCustomerInfo[0];
    let hadChooseShopList = JSON.parse(getBody.hadChooseShopList);
    let newId = '';
    let actionSqlList = [];
    // 如果是挂单保存的订单
    if (orderId) {
        newId = orderId;
        // await sql.query(`DELETE FROM XSD_MX WHERE ID = '${orderId}'`);
        // await sql.query(`DELETE FROM XSD_JS WHERE ID = '${orderId}'`);
        actionSqlList.push(`DELETE FROM XSD_MX WHERE ID = '${orderId}'`);
        actionSqlList.push(`DELETE FROM XSD_JS WHERE ID = '${orderId}'`);
    } else {


        // 生成销售订单id
        let lastOrderSql = `SELECT TOP 1 ID FROM XSD_ZB WHERE ID LIKE '${baseFn.getNowTimeId().date}${userInfo.userId}12%' ORDER BY ID DESC`;
        let oldOrder = await sql.query(lastOrderSql);
        let newSerialNum = 1;
        if (oldOrder.recordset.length !== 0) {
            let oldOrderId = oldOrder.recordset[0].ID;
            let oldSerialNum = oldOrderId.slice(oldOrderId.length - 4);
            newSerialNum = Number(oldSerialNum) + 1;
        }
        newSerialNum = newSerialNum.toString();
        newSerialNum = '0000'.slice(0, 4 - newSerialNum.length) + newSerialNum;
        newId = baseFn.getNowTimeId().date + userInfo.userId + '12' + newSerialNum;
    }
    /**
     *    写入销售订单明细表
     */

    let insertMxSql = `INSERT INTO XSD_MX (
        ID,XH,NB,YPBM,YPTM,YPMC,YPGG,JXMC,SCCJ,CDMC,PZWH,SCPH,SCRQ,YXQX,JXQX,YXQZ,JLDW,MJSL,XS,SL,
        JS,SS,YJ,YJ_HS,ZK,DJ,DJ_HS,DJ_LSJ,DJ_ZDJ,JE,RT,SE,HJ,ZKJE,CBJJ,XSCB,XSML,CKBM,CKMC,HWBH,
        JFGZ,SSYP,ZPCX,XGSL,YXFL,TSFL,KB,ZP,DZ,JF,CB,JG,UID,FHRQ,BZQK,ZLZK,FHJL,FHR2,YPLX,KCSL,SN,Notes,DJ_ZGJ) 
        `;
    let zje = 0, zss = 0, zjs = 0, zsl = 0, zhj = 0, zcb = 0, zml = 0;

    hadChooseShopList.forEach(async (item, ind) => {

        let dj = Number(item.DJ ? item.DJ : 0);
        let sl = Number(item.SL ? item.SL : 0);
        let zk = Number(item.ZK ? item.ZK : 0);
        let cbjj = Number(item.CBJJ ? item.CBJJ : 0);
        let mjsl = Number(item.MJSL ? item.MJSL : 0);
        let js = mjsl === 0 ? 0 : Math.floor(sl / mjsl);
        let ss = sl - (mjsl * js);
        let je = (dj * sl).toFixed(2);
        let hj = ((dj * zk / 100) * sl).toFixed(2);
        let zkje = je - hj;
        let xscb = (cbjj * sl).toFixed(2);
        let xsml = (hj - xscb).toFixed(2);
        zsl += sl;
        zje += Number(je);
        zss += Number(ss);
        zjs += Number(js);
        zhj += Number(hj);
        zcb += Number(xscb);
        zml += Number(xsml);
        let xhSerialNum = '00000'.slice(0, 5 - (ind + 1).toString().length) + (ind + 1);
        insertMxSql += `SELECT '${newId}',${baseFn.getNowTimeId().msDate + xhSerialNum},${ind + 1},'${item.BM}','${item.TM}','${item.MC}','${item.GG}'
            ,'${item.JXMC}','${item.SCCJ}','${item.CDMC}','${item.PZWH}','${item.SCPH}','${item.SCRQ}',${item.YXQX},180,'${item.YXQZ}','${item.JLDW}'
            ,${item.MJSL},${item.SL},${item.SL},${js},${ss},${item.DJ},${item.DJ},${item.ZK},${item.DJ},${item.DJ},${item.LSJ},${item.ZDJ},${je},0,0,${hj},${zkje}
            ,${item.CBJJ},${xscb},${xsml},'${item.CKBM}','${item.CKMC}','${item.HWBH}','${item.JFGZ}','','${item.ZPCX}',${item.XGSL},'${item.YXFL}',
            '${item.TSFL}','','F','T','T','A','F','NULL','','合格','合格','合格','','${item.YPLX}',${item.KCSL},${baseFn.getNowTimeId().msDate + xhSerialNum},'',NULL `;


        if (ind !== (hadChooseShopList.length - 1)) {
            insertMxSql += ` UNION `
        }

    });

    // 调减金额
    let tje = Number(searchTwoVal.adjustMoney ? searchTwoVal.adjustMoney : 0);
    // 优惠额
    let yhe = Number(searchTwoVal.freeMoney ? searchTwoVal.freeMoney : 0);
    zhj = zhj - tje - yhe;
    zml = zml - tje - yhe;
    // 本次积分

    let jf = parseInt(zhj / 10);
    /**
   *   改变客户的积分
   */
    let customerJfResult = await sql.query(`SELECT LJJF,SYJF FROM BM_WLDW WHERE BM = '${chooseCustomerInfo.BM}'`);
    let customerJf = customerJfResult.recordset[0];
    let ljjf = Number(customerJf.LJJF) + Number(jf);
    let syjf = Number(customerJf.SYJF) + Number(jf);
    // await sql.query(`UPDATE BM_WLDW SET LJJF = ${ljjf},SYJF = ${syjf} WHERE BM = '${chooseCustomerInfo.BM}'`);
    actionSqlList.push(`UPDATE BM_WLDW SET LJJF = ${ljjf},SYJF = ${syjf} WHERE BM = '${chooseCustomerInfo.BM}'`);
    /**
    *   插入销售总表
    */
    let payStyleStr = searchVal.payType.join(',');
    // 获取支付方式的信息
    let km = await sql.query(`SELECT MC,KMQC,BM,KMBM FROM BM_JSFS WHERE BM in (${payStyleStr})`);
    let payInfo = km.recordset;
    // 如果只有一种支付方式就写入总表里否则支付方式为空
    let zbPayType = searchVal.payType.length === 1 ? searchVal.payType[0] : '';
    let zbPayMc = searchVal.payType.length === 1 ? payInfo[0].MC : '';
    let actionZbSql = '';
    // 如果是挂单保存的订单
    if (orderId) {
        actionZbSql = `UPDATE XSD_ZB SET RQ = '${baseFn.getNowTimeId().fullDate}',JBRBM='${userInfo.userId}',JBRMC='${userInfo.mc}',JSFSBM='${zbPayType}',
        JSFSMC ='${zbPayMc}',ZDR = '${userInfo.mc}',SHR = '${userInfo.mc}',ZSL = ${zsl},ZJS = ${zjs},ZSS = ${zss},ZJE = ${zje},ZHJ= ${zhj},TJE = ${searchTwoVal.adjustMoney ? searchTwoVal.adjustMoney : 0},
        YJS= ${zhj},XJS= ${zhj},EJS=${searchTwoVal.returnMoney >= 0 ? zhj : searchTwoVal.getMoney},WJS=${searchTwoVal.returnMoney >= 0 ? 0 : searchTwoVal.returnMoney},
        ZCB=${zcb},ZML=${zml},YHE=${yhe},BCJF=${jf},SK=${searchTwoVal.getMoney ? searchTwoVal.getMoney : 0},ZL=${searchTwoVal.returnMoney ? searchTwoVal.returnMoney : 0},
        SH='T' WHERE ID = '${orderId}'`;
    } else {
        actionZbSql = `INSERT INTO XSD_ZB(ID,RQ,DWBM,DWMC,SFZH,LXDH,LXDZ,BMBM,BMMC,JBRBM,JBRMC,JSFSBM,JSFSMC,ZDR,SHR,QDR,PZH,ZDZK,SKQX,SKQZ,PJLX,PJHM,ZSL,
            ZJS,ZSS,ZJE,ZSE,ZHJ,TJE,YJS,XJS,EJS,WJS,ZZK,ZCB,ZML,YHE,DXJF,BCJF,CZJE,SK,ZL,ZY,BZ,NR,LX,FS,CS,SH,JQH,ID_JBD,ID_DHD,ID_CFD) SELECT '${newId}',
            '${baseFn.getNowTimeId().fullDate}',`;
        if ('containHempCustomerInfo' in getBody) {
            let containHempCustomerInfo = JSON.parse(getBody.containHempCustomerInfo);
            actionZbSql += `'${containHempCustomerInfo.BM}','${containHempCustomerInfo.MC}','${containHempCustomerInfo.SFZ ? containHempCustomerInfo.SFZ : ''}','${containHempCustomerInfo.DH ? containHempCustomerInfo.DH : ''}',
            '${containHempCustomerInfo.DZ ? containHempCustomerInfo.DZ : ''}',`;
        } else {
            actionZbSql += ` '${chooseCustomerInfo.BM}','${chooseCustomerInfo.MC}','${chooseCustomerInfo.SFZ ? chooseCustomerInfo.SFZ : ''}','${chooseCustomerInfo.DH ? chooseCustomerInfo.DH : ''}',
            '${chooseCustomerInfo.DZ ? chooseCustomerInfo.DZ : ''}',`;
        }
        actionZbSql += `'${partInfo.BM}','${partInfo.MC}','${userInfo.userId}','${userInfo.mc}','${zbPayType}','${zbPayMc}',
        '${userInfo.mc}','${userInfo.mc}','','',0,30,'${getMoneyTimeTo(30)}','0','',${zsl},${zjs},${zss},${zje},0,${zhj},${searchTwoVal.adjustMoney ? searchTwoVal.adjustMoney : 0},${zhj},
        ${zhj},${searchTwoVal.returnMoney >= 0 ? zhj : searchTwoVal.getMoney},${searchTwoVal.returnMoney >= 0 ? 0 : searchTwoVal.returnMoney},0,${zcb},${zml},
        ${yhe},0,${jf},0,${searchTwoVal.getMoney ? searchTwoVal.getMoney : 0},${searchTwoVal.returnMoney ? searchTwoVal.returnMoney : 0},'','','','零售',1,'','T','','','',''`;
    }
    /**
*  写入结算表
*/
    let getPayTypeMoney = {
        0: 'getMoneyCash',
        5: 'getMoneyAlipay',
        6: 'getMoneyWechat',
        7: 'getMoneyElectric'
    }
    let insertJsSql = `INSERT INTO XSD_JS(ID,XH,BM,MC,KM1BM,KM2BM,KM3BM,KMBM,KMQC,DXJF,SK,ZL,JSJE,PH,LX) `;
    payInfo.forEach((item, ind) => {
        if (Number(item.BM) === 0) {
            insertJsSql += `SELECT '${newId}',${ind + 1},'${item.BM}','${item.MC}'
            ,'','','','${item.KMBM}','${item.KMQC}',NULL,${searchTwoVal[getPayTypeMoney[item.BM]]},${searchTwoVal.returnMoney},${Number(searchTwoVal[getPayTypeMoney[item.BM]]) - Number(searchTwoVal.returnMoney)},'NULL',${searchVal.saleType}`;
        } else {
            insertJsSql += `SELECT '${newId}',${ind + 1},'${item.BM}','${item.MC}'
            ,'','','','${item.KMBM}','${item.KMQC}',NULL,${searchTwoVal[getPayTypeMoney[item.BM]]},NULL,${searchTwoVal[getPayTypeMoney[item.BM]]},'NULL',${searchVal.saleType}`;
        }

        if (ind !== (payInfo.length - 1)) {
            insertJsSql += ` UNION `
        }
    });
    // 如果有处方登记
    if (getBody.hasOwnProperty('customerInfo')) {
        let customerInfo = JSON.parse(getBody.customerInfo);
        let prescriptionList = JSON.parse(getBody.prescriptionList);

        const files = ctx.request.files;
        /**
    *   插入处方单明细
    */
        let insertCfdMxSql = `INSERT INTO CFD_MX(ID,XH,NB,YPBM,YPMC,YPGG,JXMC,SCCJ,CDMC,JLDW,SL,YFYL,YL,DW,YF,PL,TS,JL,ZL) `;
        // 处方单商品数量
        let cfdSl = 0;
        prescriptionList.forEach((item, ind) => {
            cfdSl += Number(item.SL);
            let xhSerialNum = '00000'.slice(0, 5 - (ind + 1).toString().length) + (ind + 1);
            if (ind == prescriptionList.length - 1) {
                insertCfdMxSql += `SELECT '${newId}',${baseFn.getNowTimeId().msDate + xhSerialNum},${ind + 1},'${item.BM}','${item.MC}','${item.GG}','${item.JXMC}','${item.SCCJ}','${item.CDMC}','${item.JLDW}',${item.SL},'${item.YFYL}',${item.YL},'${item.DW}','${item.YF}','${item.PL}',${item.TS},${item.JL},${item.ZL}`;
            } else {
                insertCfdMxSql += `SELECT '${newId}',${baseFn.getNowTimeId().msDate + xhSerialNum},${ind + 1},'${item.BM}','${item.MC}','${item.GG}','${item.JXMC}','${item.SCCJ}','${item.CDMC}','${item.JLDW}',${item.SL},'${item.YFYL}',${item.YL},'${item.DW}','${item.YF}','${item.PL}',${item.TS},${item.JL},${item.ZL}  UNION `;

            }
        });
        // 上传处方照
        let picNameList = [];
        for (let item in files) {
            picNameList.push(storagePic(files[item], item))
        }
        /**
   *  插入处方总表
   */
        let insertCfdZbSql = `INSERT INTO CFD_ZB(ID,RQ,BMBM,BMMC,BM,XM,CB,XB,SR,NL,
            TZ,SL,ZDJG,DZ,DH,SFZH,YYFW,CFLY,CFLX,CFYS,SFYS,TPRY,SFRQ,SFZT,ZDR,PZ,BZ,
            YJ,BL,SH,YY,PIC1,PIC2,PIC3,PIC4,PIC5,JBBM) SELECT '${newId}','${baseFn.getNowTimeId().fullDate}','${partInfo.BM}','${partInfo.MC}',
            '${customerInfo.BM}','${customerInfo.MC}','','${customerInfo.XB}','${customerInfo.SR}','${customerInfo.NL}',
            '','${cfdSl}','${customerInfo.ZDJG}','${customerInfo.DZ}','${customerInfo.DH}','${customerInfo.SFZ}','','${customerInfo.CFLY}',
            '${customerInfo.CFLX}','${customerInfo.CFYS}','${customerInfo.SFYS}','${customerInfo.TPRY}','${customerInfo.SFRQ}','1','${userInfo.mc}',
            '${customerInfo.YSPZ}','${customerInfo.BZ}','${customerInfo.YJ}',${customerInfo.BL},'F','T','${picNameList[0] ? picNameList[0] : 'NULL'}','${picNameList[1] ? picNameList[1] : 'NULL'}',
            '${picNameList[2] ? picNameList[2] : 'NULL'}','${picNameList[3] ? picNameList[3] : 'NULL'}','${picNameList[4] ? picNameList[4] : 'NULL'}',''`;

        // let cfdmx = await sql.query(insertCfdMxSql);
        // await sql.query(insertCfdZbSql);
        actionSqlList.push(insertCfdMxSql);
        actionSqlList.push(insertCfdZbSql);


    }
    // let xsdMxReuslt = await sql.query(insertMxSql);
    actionSqlList.push(insertMxSql);
    /**
     * 如果插入销售明细表后减库存
     *  */
    // if (xsdMxReuslt.rowsAffected[0] > 0) {
    // hadChooseShopList.forEach(async (item, ind) => {
    /**
*   减库存
*/
    for (let item of hadChooseShopList) {
        let kcslResult = await sql.query(`SELECT KCSL,KYSL,CBJJ FROM KC_KCDTB WHERE BMBM ='${partInfo.BM}' AND YPBM = '${item.BM}' AND SCPH = '${item.SCPH}' AND CKBM = '${item.CKBM}'`);
        let kcsl = kcslResult.recordset[0].KCSL;
        let kysl = kcslResult.recordset[0].KYSL;
        let cbjj = kcslResult.recordset[0].CBJJ;
        // await sql.query(`UPDATE KC_KCDTB SET KCSL = ${kcsl - item.SL},KYSL = ${kysl - item.SL},KCJE = ${(kcsl - item.SL) * cbjj} WHERE BMBM ='${partInfo.BM}' AND YPBM = '${item.BM}' AND SCPH = '${item.SCPH}' AND CKBM = '${item.CKBM}'`);
        actionSqlList.push(`UPDATE KC_KCDTB SET KCSL = ${kcsl - item.SL},KYSL = ${kysl - item.SL},KCJE = ${(kcsl - item.SL) * cbjj} WHERE BMBM ='${partInfo.BM}' AND YPBM = '${item.BM}' AND SCPH = '${item.SCPH}' AND CKBM = '${item.CKBM}'`);
    };
    // }
    // await sql.query(insertJsSql);
    // let result = await sql.query(actionZbSql);
    actionSqlList.push(insertJsSql);
    actionSqlList.push(actionZbSql);
    // let result = await sql.query();
    let lastSql = `SET XACT_ABORT ON Begin Tran ${actionSqlList.join(' ')} Commit Tran `;
    let lastResult = await sql.query(lastSql);


    if (lastResult.rowsAffected[0] > 0) {
        ctx.body = { success: true, orderId: newId }
    } else {
        ctx.body = { success: false }
    }
}


/**
 * 挂单保存信息
 */
const keepStoreSalesHangeInfo = async (ctx, next) => {
    const getBody = ctx.request.body;
    let partInfo = JSON.parse(getBody.partInfo);
    let userInfo = JSON.parse(getBody.userInfo);
    let searchVal = JSON.parse(getBody.searchVal);
    let chooseCustomerInfo = searchVal.chooseCustomerInfo[0];
    let hadChooseShopList = JSON.parse(getBody.hadChooseShopList);
    let actionSqlList = [];
    //     // 生成销售订单id
    let lastOrderSql = `SELECT TOP 1 ID FROM XSD_ZB WHERE ID LIKE '${baseFn.getNowTimeId().date}${userInfo.userId}12%' ORDER BY ID DESC`;
    let oldOrder = await sql.query(lastOrderSql);
    let newSerialNum = 1;
    if (oldOrder.recordset.length !== 0) {
        let oldOrderId = oldOrder.recordset[0].ID;
        let oldSerialNum = oldOrderId.slice(oldOrderId.length - 4);
        newSerialNum = Number(oldSerialNum) + 1;
    }
    newSerialNum = newSerialNum.toString();
    newSerialNum = '0000'.slice(0, 4 - newSerialNum.length) + newSerialNum;
    let newId = baseFn.getNowTimeId().date + userInfo.userId + '12' + newSerialNum;
    /**
     *    写入销售订单明细表
     */

    let insertMxSql = `INSERT INTO XSD_MX (
        ID,XH,NB,YPBM,YPTM,YPMC,YPGG,JXMC,SCCJ,CDMC,PZWH,SCPH,SCRQ,YXQX,JXQX,YXQZ,JLDW,MJSL,XS,SL,
        JS,SS,YJ,YJ_HS,ZK,DJ,DJ_HS,DJ_LSJ,DJ_ZDJ,JE,RT,SE,HJ,ZKJE,CBJJ,XSCB,XSML,CKBM,CKMC,HWBH,
        JFGZ,SSYP,ZPCX,XGSL,YXFL,TSFL,KB,ZP,DZ,JF,CB,JG,UID,FHRQ,BZQK,ZLZK,FHJL,FHR2,YPLX,KCSL,SN,Notes,DJ_ZGJ) 
        `;
    let zje = 0, zss = 0, zjs = 0, zsl = 0, zhj = 0, zcb = 0, zml = 0;

    hadChooseShopList.forEach(async (item, ind) => {

        let dj = Number(item.DJ ? item.DJ : 0);
        let sl = Number(item.SL ? item.SL : 0);
        let zk = Number(item.ZK ? item.ZK : 0);
        let cbjj = Number(item.CBJJ ? item.CBJJ : 0);
        let mjsl = Number(item.MJSL ? item.MJSL : 0);
        let js = mjsl === 0 ? 0 : Math.floor(sl / mjsl);
        let ss = sl - (mjsl * js);
        let je = (dj * sl).toFixed(2);
        let hj = ((dj * zk / 100) * sl).toFixed(2);
        let zkje = je - hj;
        let xscb = (cbjj * sl).toFixed(2);
        let xsml = (hj - xscb).toFixed(2);
        zsl += sl;
        zje += Number(je);
        zss += Number(ss);
        zjs += Number(js);
        zhj += Number(hj);
        zcb += Number(xscb);
        zml += Number(xsml);
        let xhSerialNum = '00000'.slice(0, 5 - (ind + 1).toString().length) + (ind + 1);
        insertMxSql += `SELECT '${newId}',${baseFn.getNowTimeId().msDate + xhSerialNum},${ind + 1},'${item.BM}','${item.TM}','${item.MC}','${item.GG}'
            ,'${item.JXMC}','${item.SCCJ}','${item.CDMC}','${item.PZWH}','${item.SCPH}','${item.SCRQ}',${item.YXQX},180,'${item.YXQZ}','${item.JLDW}'
            ,${item.MJSL},${item.SL},${item.SL},${js},${ss},${item.DJ},${item.DJ},${item.ZK},${item.DJ},${item.DJ},${item.LSJ},${item.ZDJ},${je},0,0,${hj},${zkje}
            ,${item.CBJJ},${xscb},${xsml},'${item.CKBM}','${item.CKMC}','${item.HWBH}','${item.JFGZ}','','${item.ZPCX}',${item.XGSL},'${item.YXFL}',
            '${item.TSFL}','','F','T','T','A','F','NULL','','合格','合格','合格','','${item.YPLX}',${item.KCSL},${baseFn.getNowTimeId().msDate + xhSerialNum},'',NULL `;


        if (ind !== (hadChooseShopList.length - 1)) {
            insertMxSql += ` UNION `
        }

    });

    /**
    *   插入销售总表
    */

    let insertZbSql = `INSERT INTO XSD_ZB(ID,RQ,DWBM,DWMC,SFZH,LXDH,LXDZ,BMBM,BMMC,JBRBM,JBRMC,JSFSBM,JSFSMC,ZDR,SHR,QDR,PZH,ZDZK,SKQX,SKQZ,PJLX,PJHM,ZSL,
        ZJS,ZSS,ZJE,ZSE,ZHJ,TJE,YJS,XJS,EJS,WJS,ZZK,ZCB,ZML,YHE,DXJF,BCJF,CZJE,SK,ZL,ZY,BZ,NR,LX,FS,CS,SH,JQH,ID_JBD,ID_DHD,ID_CFD) SELECT '${newId}',
        '${baseFn.getNowTimeId().fullDate}',`;
    if ('containHempCustomerInfo' in getBody) {
        let containHempCustomerInfo = JSON.parse(getBody.containHempCustomerInfo);
        insertZbSql += `'${containHempCustomerInfo.BM}','${containHempCustomerInfo.MC}','${containHempCustomerInfo.SFZ}','${containHempCustomerInfo.DH}',
        '${containHempCustomerInfo.DZ}',`;
    } else {
        insertZbSql += ` '${chooseCustomerInfo.BM}','${chooseCustomerInfo.MC}','${chooseCustomerInfo.SFZ}','${chooseCustomerInfo.DH}',
        '${chooseCustomerInfo.DZ}',`;
    }
    insertZbSql += `'${partInfo.BM}','${partInfo.MC}','${userInfo.userId}','${userInfo.mc}','','',
    '${userInfo.mc}','','','',0,30,'${getMoneyTimeTo(30)}','0','',${zsl},${zjs},${zss},${zje},0,${zhj}, 0,${zhj},
    ${zhj},0,0,0,${zcb},${zml},
    0,0,0,0,0,0,'','','','零售',1,'','F','','','',''`;
    actionSqlList.push(insertMxSql);
    actionSqlList.push(insertZbSql);
    // let xsdMxReuslt = await sql.query(insertMxSql);
    // let result = await sql.query(insertZbSql);
    let lastSql = `SET XACT_ABORT ON Begin Tran ${actionSqlList.join(' ')} Commit Tran `;
    let lastResult = await sql.query(lastSql);

    if (lastResult.rowsAffected[0] > 0) {
        ctx.body = { success: true, orderId: newId }
    } else {
        ctx.body = { success: false }
    }
}

// 含麻药品当日购买数量的限制

const getContainHempLimitcount = async (ctx, next) => {
    const body = ctx.request.body;
    let selectSql = `SELECT (Y.XGSL-ISNULL(T1.GMSL,0)) AS XGSL ,Y.BM FROM BM_YP Y LEFT JOIN (SELECT M.YPBM,SUM(M.SL) AS GMSL FROM XSD_MX M LEFT JOIN XSD_ZB Z 
    ON M.ID = Z.ID WHERE M.YPBM = '${body.YPBM}' AND Z.SFZH = '${body.SFZ}' AND Z.RQ >= '${baseFn.getNowTimeId().halfDate} 00:00:00' AND Z.RQ<= '${baseFn.getNowTimeId().halfDate} 23:59:59' 
    GROUP BY M.YPBM) T1 ON Y.BM = T1.YPBM WHERE Y.BM = '${body.YPBM}'`;
    let result = await sql.query(selectSql);
    if (result.rowsAffected[0] === 1) {
        ctx.body = { success: true, result: result.recordset[0].XGSL }
    } else {
        ctx.body = { success: false }
    }
}

// 获取未审核的订单

const getStoreSalesNotAuditedOrder = async (ctx, next) => {
    const body = ctx.request.body;
    let selectZbSql = `SELECT RQ,ID,DWMC,ZSL,ZJE,BMMC,JBRMC FROM XSD_ZB WHERE BMBM = '${body.BMBM}' AND RQ >= '2019-07-26' AND SH = 'F' ORDER BY ID DESC`;

    let zbResult = await sql.query(selectZbSql);

    ctx.body = { result: zbResult.recordset }

}
// 获取未审核的订单

const getStoreSalesOrder = async (ctx, next) => {
    const body = ctx.request.body;
    let selectZbSql = `SELECT * FROM XSD_ZB WHERE ID = '${body.id}'`;
    let selectMxSql = `SELECT * FROM XSD_MX WHERE ID = '${body.id}'`;
    let mxResult = await sql.query(selectMxSql);
    let zbResult = await sql.query(selectZbSql);

    ctx.body = { zbResult: zbResult.recordset, mxResult: mxResult.recordset }

}


module.exports = {
    'POST /getLoginPartInfo': getLoginPartInfo,
    'POST /getStoreShopInfo': getStoreShopInfo,
    'POST /getStoreSalesScph': getStoreSalesScph,
    'POST /getStoreSalesNotAuditedOrder': getStoreSalesNotAuditedOrder,
    'POST /keepStoreSalesInfo': keepStoreSalesInfo,
    'POST /getStoreSalesNewShopPrice': getStoreSalesNewShopPrice,
    'POST /getCustomerInfo': getCustomerInfo,
    'POST /getStoreSalesOrder': getStoreSalesOrder,
    'POST /keepStoreSalesHangeInfo': keepStoreSalesHangeInfo,
    'POST /getContainHempLimitcount': getContainHempLimitcount


}